package org.ruoyi.system.service.impl;

import org.ruoyi.common.core.utils.MapstructUtils;
import org.ruoyi.core.page.TableDataInfo;
import org.ruoyi.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.ruoyi.system.domain.bo.SysFileInfoBo;
import org.ruoyi.system.domain.vo.SysFileInfoVo;
import org.ruoyi.system.domain.SysFileInfo;
import org.ruoyi.system.mapper.SysFileInfoMapper;
import org.ruoyi.system.service.ISysFileInfoService;
import org.ruoyi.common.core.utils.StringUtils;
import org.ruoyi.common.core.utils.DateUtils;
import org.ruoyi.common.core.utils.file.FileUtils;
import org.ruoyi.common.core.utils.file.MimeTypeUtils;
import org.ruoyi.common.core.utils.OsUtils;
import org.ruoyi.common.core.exception.ServiceException;
import org.ruoyi.common.satoken.utils.LoginHelper;
import cn.hutool.core.io.FileUtil;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.annotation.PostConstruct;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 文件记录Service业务层处理
 *
 * @author ageerle
 * @date 2025-04-29
 */
@RequiredArgsConstructor
@Service
public class SysFileInfoServiceImpl implements ISysFileInfoService {

    private final SysFileInfoMapper baseMapper;

    @Value("${ruoyi.file.upload-path-win:D:/ruoyi/uploadPath}")
    private String uploadPathWin;

    @Value("${ruoyi.file.upload-path-linux:/data/ruoyi/uploadPath}")
    private String uploadPathLinux;

    @Value("${ruoyi.file.allowed-types:doc,docx,xls,xlsx,ppt,pptx,pdf,zip,rar,txt,jpg,jpeg,png,gif}")
    private String allowedTypes;

    /**
     * 获取当前操作系统对应的上传根路径
     */
    private String getUploadPath() {
        return OsUtils.isWindows() ? uploadPathWin : uploadPathLinux;
    }

    @PostConstruct
    public void init() {
        // 创建上传目录
        FileUtil.mkdir(new File(getUploadPath()));
    }

    /**
     * 查询文件记录
     */
    @Override
    public SysFileInfoVo queryById(String id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询文件记录列表
     */
    @Override
    public TableDataInfo<SysFileInfoVo> queryPageList(SysFileInfoBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SysFileInfo> lqw = buildQueryWrapper(bo);
        Page<SysFileInfoVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询文件记录列表
     */
    @Override
    public List<SysFileInfoVo> queryList(SysFileInfoBo bo) {
        LambdaQueryWrapper<SysFileInfo> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<SysFileInfo> buildQueryWrapper(SysFileInfoBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<SysFileInfo> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getUrl()), SysFileInfo::getUrl, bo.getUrl());
        lqw.eq(bo.getSize() != null, SysFileInfo::getSize, bo.getSize());
        lqw.like(StringUtils.isNotBlank(bo.getFilename()), SysFileInfo::getFilename, bo.getFilename());
        lqw.like(StringUtils.isNotBlank(bo.getOriginalFilename()), SysFileInfo::getOriginalFilename, bo.getOriginalFilename());
        lqw.eq(StringUtils.isNotBlank(bo.getBasePath()), SysFileInfo::getBasePath, bo.getBasePath());
        lqw.eq(StringUtils.isNotBlank(bo.getPath()), SysFileInfo::getPath, bo.getPath());
        lqw.eq(StringUtils.isNotBlank(bo.getExt()), SysFileInfo::getExt, bo.getExt());
        lqw.eq(StringUtils.isNotBlank(bo.getUserId()), SysFileInfo::getUserId, bo.getUserId());
        lqw.eq(StringUtils.isNotBlank(bo.getFileType()), SysFileInfo::getFileType, bo.getFileType());
        lqw.eq(StringUtils.isNotBlank(bo.getAttr()), SysFileInfo::getAttr, bo.getAttr());
        lqw.eq(StringUtils.isNotBlank(bo.getUpdateIp()), SysFileInfo::getUpdateIp, bo.getUpdateIp());
        return lqw;
    }

    /**
     * 新增文件记录
     */
    @Override
    public Boolean insertByBo(SysFileInfoBo bo) {
        SysFileInfo add = MapstructUtils.convert(bo, SysFileInfo.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改文件记录
     */
    @Override
    public Boolean updateByBo(SysFileInfoBo bo) {
        SysFileInfo update = MapstructUtils.convert(bo, SysFileInfo.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SysFileInfo entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除文件记录
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 上传文件
     *
     * @param file 文件
     * @param bizType 业务类型(例如: audit/avatar/doc等)
     * @return 文件信息
     */
    @Override
    public SysFileInfo upload(MultipartFile file, String bizType) {
        // 1. 校验文件
        String originalFilename = file.getOriginalFilename();
        if (file.isEmpty() || StringUtils.isBlank(originalFilename)) {
            throw new ServiceException("上传文件不能为空");
        }

        // 2. 校验文件类型
        String extension = StringUtils.substring(originalFilename, originalFilename.lastIndexOf(".") + 1);
        if (!isAllowedExtension(extension)) {
            throw new ServiceException("不支持的文件类型: " + extension);
        }

        try {
            // 3. 生成文件路径
            String fileName = UUID.randomUUID().toString() + "." + extension;
            String relativePath = bizType + "/" + DateUtils.datePath() + "/" + fileName;
            String absolutePath = FilenameUtils.normalize(getUploadPath() + File.separator + relativePath);
            
            // 4. 确保目录存在并保存文件
            File uploadFile = new File(absolutePath);
            FileUtil.mkdir(uploadFile.getParentFile());
            file.transferTo(uploadFile);

            // 5. 保存文件信息
            SysFileInfo fileInfo = new SysFileInfo();
            fileInfo.setUrl(relativePath);
            fileInfo.setSize(uploadFile.length());
            fileInfo.setFilename(fileName);
            fileInfo.setOriginalFilename(originalFilename);
            fileInfo.setBasePath(getUploadPath());
            fileInfo.setPath(relativePath.replace("\\", "/"));
            fileInfo.setExt(extension);
            fileInfo.setFileType(bizType);
            fileInfo.setUserId(LoginHelper.getUserId().toString());
            fileInfo.setCreateBy(LoginHelper.getUserId());
            fileInfo.setCreateTime(new Date());
            baseMapper.insert(fileInfo);

            return fileInfo;
        } catch (IOException e) {
            throw new ServiceException("文件上传失败: " + e.getMessage());
        }
    }

    /**
     * 下载文件
     */
    @Override
    public void download(String fileId, HttpServletResponse response) {
        SysFileInfo fileInfo = baseMapper.selectById(fileId);
        if (fileInfo == null) {
            throw new ServiceException("文件不存在");
        }

        // 使用FilenameUtils.normalize确保路径分隔符正确
        String filePath = FilenameUtils.normalize(fileInfo.getBasePath() + File.separator + fileInfo.getPath());
        try {
            File file = new File(filePath);
            if (!file.exists()) {
                throw new ServiceException("文件不存在");
            }
            response.setContentType(MimeTypeUtils.getContentType(fileInfo.getExt()));
            FileUtils.setAttachmentResponseHeader(response, fileInfo.getOriginalFilename());
            FileUtil.writeToStream(file, response.getOutputStream());
        } catch (IOException e) {
            throw new ServiceException("文件下载失败: " + e.getMessage());
        }
    }

    /**
     * 删除文件
     */
    @Override
    public Boolean deleteFile(String fileId) {
        SysFileInfo fileInfo = baseMapper.selectById(fileId);
        if (fileInfo != null) {
            // 使用FilenameUtils.normalize确保路径分隔符正确
            String filePath = FilenameUtils.normalize(fileInfo.getBasePath() + File.separator + fileInfo.getPath());
            FileUtil.del(filePath);
            return baseMapper.deleteById(fileId) > 0;
        }
        return false;
    }

    /**
     * 检查文件类型是否允许
     */
    private boolean isAllowedExtension(String extension) {
        return Arrays.asList(allowedTypes.split(",")).contains(extension.toLowerCase());
    }
}
